package com.zqx.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zqx.domain.*;
import com.zqx.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
public class AccountController {
    @Autowired
    private UserService userService;

    @Autowired
    private StudentService studentService;
    @Autowired
    private SupervisorService supervisorService;
    @Autowired
    private FixService fixService;
    @Autowired
    private MoveService moveService;
    @Value("${location}")
    private String location;

    @RequestMapping("login")
    public String login(String username, String password, Model model, HttpSession session) {
        if (username.equals("admin")) {
            boolean b = userService.login(username, password);
            if (b) {
                //条件构造器：MP用来查询一些特殊的字段
                QueryWrapper<User> qw = new QueryWrapper<>();
                qw.eq("username", username);
                User user = userService.getOne(qw);
                session.setAttribute("currentUser", username);
                session.setAttribute("userid", user.getId());
                session.setAttribute("password", password);
                session.setAttribute("email", user.getEmail());
                session.setAttribute("phone", user.getPhone());
                session.setAttribute("image", user.getImage());
                //String currentUser = (String) session.getAttribute("currentUser");
                //主页数量统计
                List<Student> list1 = studentService.list(null);
                List<Supervisor> list2 = supervisorService.list(null);
                List<Move> list3 = moveService.list(null);
                List<Fix> list4 = fixService.list(null);
                model.addAttribute("peopleCount",list1.size());
                model.addAttribute("adminCount",list2.size());
                model.addAttribute("moveCount",list3.size());
                model.addAttribute("fixCount",list4.size());
                model.addAttribute("studentList",list1);
                return "dormMainMenu";
            } else {
                model.addAttribute("msg", "用户名密码错误");
                return "index";
            }
        } else {
            boolean b = studentService.login(username, password);
            if (b) {
                //条件构造器：MP用来查询一些特殊的字段
                QueryWrapper<Student> qw = new QueryWrapper<>();
                qw.eq("sname", username);
                Student user = studentService.getOne(qw);
                session.setAttribute("currentUser", username);
                session.setAttribute("userid", user.getId());
                session.setAttribute("password", user.getPassword());
                session.setAttribute("email", user.getEmail());
                session.setAttribute("phone", user.getPhone());
                session.setAttribute("image", user.getSimage());
                //主页数量统计
                List<Student> list1 = studentService.list(null);
                List<Supervisor> list2 = supervisorService.list(null);
                List<Move> list3 = moveService.list(null);
                List<Fix> list4 = fixService.list(null);
                model.addAttribute("peopleCount",list1.size());
                model.addAttribute("adminCount",list2.size());
                model.addAttribute("moveCount",list3.size());
                model.addAttribute("fixCount",list4.size());
                model.addAttribute("studentList",list1);
                return "dormMainMenu1";
            } else {
                model.addAttribute("msg", "用户名密码错误");
                return "index";
            }
        }
    }
    //管理员的主页面
    @RequestMapping("home")
    public String home(Model model){
        //主页数量统计
        List<Student> list1 = studentService.list(null);
        List<Supervisor> list2 = supervisorService.list(null);
        List<Move> list3 = moveService.list(null);
        List<Fix> list4 = fixService.list(null);
        model.addAttribute("peopleCount",list1.size());
        model.addAttribute("adminCount",list2.size());
        model.addAttribute("moveCount",list3.size());
        model.addAttribute("fixCount",list4.size());
        model.addAttribute("studentList",list1);
        return "dormMainMenu";
    }
    //普通用户的主页面
    @RequestMapping("homeUser")
    public String homeUser(Model model){
        //主页数量统计
        List<Student> list1 = studentService.list(null);
        List<Supervisor> list2 = supervisorService.list(null);
        List<Move> list3 = moveService.list(null);
        List<Fix> list4 = fixService.list(null);
        model.addAttribute("peopleCount",list1.size());
        model.addAttribute("adminCount",list2.size());
        model.addAttribute("moveCount",list3.size());
        model.addAttribute("fixCount",list4.size());
        model.addAttribute("studentList",list1);
        return "dormMainMenu1";
    }
    //用户注册
    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }
    @RequestMapping("toLogin")
    public String toLogin(){
        return "index";
    }
    @RequestMapping("register")
    public String register(String userName,String userPwd,String confirmPwd,Model model){
        if (!userPwd.equals(confirmPwd)){
            model.addAttribute("msg","两次输入的密码不一致");
            return "register";
        }else {
            Student student = new Student();
            student.setSname(userName);
            student.setPassword(DigestUtil.md5Hex(userPwd));
            boolean save = studentService.save(student);
            return "index";
        }
    }
    //用户退出
    @RequestMapping("logout")
    public String logout(){
        return "index";
    }
    //个人信息
    @RequestMapping("profile")
    public String profile(HttpSession session,Model model){
        String currentUser = (String) session.getAttribute("currentUser");
        String password = (String) session.getAttribute("password");
        if (currentUser.equals("admin")){
            QueryWrapper<User> qw = new QueryWrapper<>();
            qw.eq("username",currentUser);
            User one = userService.getOne(qw);
            one.setPassword(password);
            model.addAttribute("user", one);
            return "admin-profile";
        }else {
            QueryWrapper<Student> qw = new QueryWrapper<>();
            qw.eq("sname", currentUser);
            Student one = studentService.getOne(qw);
            one.setPassword(password);
            model.addAttribute("user",one);
            return "user-profile";
        }
    }
    //修改管理员用户信息
    @RequestMapping("updateAdminProfile")
    public String updateAdminProfile(User user, MultipartFile file){
        if (!file.isEmpty()){
            transfileAdmin(user,file);
        }
        user.setPassword(DigestUtil.md5Hex(user.getPassword()));
        boolean b = userService.updateById(user);
        return "redirect:/profile";
    }
    private void transfileAdmin(User user, MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(index);
        String s = System.nanoTime() + "";
        String path = substring+s;
        File file1 = new File(location);
        if (!file1.exists()){
            file1.mkdirs();
        }
        File file2 = new File(file1, path);
        try {
            file.transferTo(file2);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        user.setImage(path);
    }
    //修改用户信息
    @RequestMapping("updateStudentProfile")
    public String updateStudentProfile(Student student, MultipartFile file){
        if (!file.isEmpty()){
            transfileStudent(student,file);
        }
        student.setPassword(DigestUtil.md5Hex(student.getPassword()));
        boolean b = studentService.updateById(student);
        return "redirect:/profile";
    }

    private void transfileStudent(Student student, MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(index);
        String s = System.nanoTime() + "";
        String path = substring+s;
        File file1 = new File(location);
        if (!file1.exists()){
            file1.mkdirs();
        }
        File file2 = new File(file1, path);
        try {
            file.transferTo(file2);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        student.setSimage(path);
    }
}
